package com.bw.ivideo.testmvi.home.viewmodel

import androidx.lifecycle.viewModelScope
import com.bw.ivideo.testmvi.home.intent.HomeSimpleIntent
import com.bw.ivideo.testmvi.home.model.repository.HomeRepository
import com.bw.ivideo.testmvi.home.state.HomeSimpleTypeState
import com.bw.lib_common.base.BaseViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author ytx
 * @date 2025-10-16 10:19
 * @description
 */
@HiltViewModel
class HomeViewModel @Inject constructor(private val repository: HomeRepository) :BaseViewModel<HomeSimpleIntent>() {

    private var simpleTypeStateFlow  = MutableStateFlow<HomeSimpleTypeState>(HomeSimpleTypeState.Init)
    val simpleTypeStateFlow_ = simpleTypeStateFlow.asStateFlow()

    /**
     * 1.根据不同的意图处理不同数据请求
     */
    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is HomeSimpleIntent.getSimpleType -> {//请求视频类型
                        getSimpleType()
                    }
                    is HomeSimpleIntent.getSimpleVideoByChannelId -> {//根据id获得视频信息

                    }
                }
            }
        }
    }

    /**
     * 2.请求的结果更新state
     */
    fun getSimpleType(){
        viewModelScope.launch {
           repository.getSimpleType()
               .catch { e ->
                    simpleTypeStateFlow.value = HomeSimpleTypeState.Error(e.message.toString())
               }.filter {
                   it != null
               }.collect{
                   if (it.code == 200){
                       if (it.data.isNotEmpty()){
                           simpleTypeStateFlow.value = HomeSimpleTypeState.Success(it.data)
                       }else{
                           simpleTypeStateFlow.value = HomeSimpleTypeState.Empty
                       }
                   }else{
                       simpleTypeStateFlow.value = HomeSimpleTypeState.Error(it.msg)
                   }
               }
        }
    }
}